from django.utils import timezone
from django.core.mail import send_mail
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from moderation.models import TagChangeRequest, TagDependencyChangeRequest
from rest_framework.decorators import authentication_classes, permission_classes
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.permissions import IsAdminUser
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from tag.models import Tag, AlgorithmTag
from problems.models import Problem
from utils.logging_utils import log_request_response


# 用户提交希望修改的题目及其标签，提供添加和删除两种模式
@api_view(['POST'])
@authentication_classes([JWTAuthentication])  # 使用 Token 认证
@permission_classes([IsAuthenticated])
@log_request_response
def submit_tag_change_request(request):
    user = request.user
    problem_number = request.data.get('problem_number')
    tag_index = request.data.get('tag_index')
    add_or_delete = request.data.get('add_or_delete')

    try:
        problem = Problem.objects.get(problem_number=problem_number)
        tag = Tag.objects.get(index=tag_index)
    except Problem.DoesNotExist:
        return Response({"error": "Problem not found"}, status=status.HTTP_404_NOT_FOUND)
    except Tag.DoesNotExist:
        return Response({"error": "Tag not found"}, status=status.HTTP_404_NOT_FOUND)

    # 创建标签变更请求
    tag_change_request = TagChangeRequest.objects.create(
        user=user,
        problem=problem,
        tag=tag,
        add_or_delete=add_or_delete,
    )

    return Response({"message": "Tag change request submitted successfully."}, status=status.HTTP_201_CREATED)


# 用户提交希望修改的依赖关系，提供添加和删除两种模式
@api_view(['POST'])
@authentication_classes([JWTAuthentication])  # 使用 Token 认证
@permission_classes([IsAuthenticated])  # 用户必须登录
@log_request_response
def submit_tag_dependency_change_request(request):
    user = request.user
    source_tag_index = request.data.get('source_tag_index')
    target_tag_index = request.data.get('target_tag_index')
    weight = request.data.get('weight', 1.0)  # 默认权重为 1.0
    add_or_delete = request.data.get('add_or_delete')

    try:
        source_tag = AlgorithmTag.objects.get(index=source_tag_index)
        target_tag = AlgorithmTag.objects.get(index=target_tag_index)
    except AlgorithmTag.DoesNotExist:
        return Response({"error": "Source or target tag not found"}, status=404)

    # 创建依赖变更请求
    tag_dependency_change_request = TagDependencyChangeRequest.objects.create(
        user=user,
        source_tag=source_tag,
        target_tag=target_tag,
        weight=weight,
        add_or_delete=add_or_delete,
    )

    return Response({"message": "Tag dependency change request submitted successfully."}, status=201)